<?php
namespace app\model\question;

use think\Model;
use app\model\user\ZxlTalentUserModel;

class ZxlKnowStoreQuestionPracticeModel extends Model
{
    protected $name = 'zxl_know_store_question_practice';

    const STATUSSEXAMTR = [
        0 => "待交卷",
        1 => "批改中",
        2 => "未完成",
        3 => "已批改"
    ];

    /**
     * 关联用户信息
     */
    public function user(){
        return $this->hasOne(ZxlTalentUserModel::class, "id", "user_id");
    }

    /**
     * 更新做题记录
     * 
     * @param $practice_type professional考试、chapter题库章节练习
     * @return int
     */
    public static function save_practice($user_id, $m_id, $product_id, $target_id, $total_question, $practice_type='professional', $question_ids = [], $mode = '')
    {
        $where = function($q)use($user_id,$m_id,$product_id,$target_id,$practice_type){
            $q->where('m_id', $m_id);
            $q->where('lib_id', $product_id);
            $q->where('target_id', $target_id);
            $q->where('user_id', $user_id);
            $q->where('practice_type', $practice_type);
        };
        // 最新做题记录
        $practice = ZxlKnowStoreQuestionPracticeModel::where($where)->order('create_time desc')->find();
        if (!$practice || ($practice && $practice['status'] > 0)) {
            $practice = new ZxlKnowStoreQuestionPracticeModel();
            $practice->user_id = $user_id;
            $practice->m_id = $m_id;
            $practice->practice_type = $practice_type; // 考试
            $practice->target_id = $target_id;
            $practice->lib_id = $product_id;
            $practice->date = date('Y-m-d');
            $practice->total_question = $total_question;
            $practice->create_time = time();
        }
        if ($practice_type == 'chapter') {
            if ($question_ids) {
                $practice->question_ids = implode(",", $question_ids);  
            }
            if ($mode == 0) {
                $practice->mode = 'random';
            } else {
                $practice->mode = 'sort';
            }
        }
        $practice->save();
        return $practice->id;
    }
}